package com.bytedance.douyinclouddemo.utils;


import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InternalCallUtil {

    // GET请求调用 path(例)：/api/get_result?num=1
    public static String InternalCallGet(String path, String toServiceID, HashMap<String, String> paramMap, HashMap<String, String> headers) throws Exception {
        // 从环境变量中获取源服务id（即当前服务id）
        String fromServiceID = System.getenv("SERVICE_ID");
        
        // 构造url
        String url = String.format("http://%s-%s.inner-call.dyc.ivolces.com%s", fromServiceID, toServiceID, path);

        // 构造POST请求体
        HttpGet httpGet = new HttpGet(url);
        // 表单参数
        List<NameValuePair> nvps = new ArrayList<>();
        // GET 请求参数
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }

        // 将参数增加到请求 URL 中
        try {
            URI uriVariable = new URIBuilder(new URI(url))
                    .addParameters(nvps)
                    .build();
            httpGet.setURI(uriVariable);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

        // 添加header
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.addHeader(entry.getKey(), entry.getValue());
        }

        // 执行GET请求并读取响应
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();
                // 判断http状态码是否成功
                if (statusCode != 200) {
                    response.close();
                    throw new Exception(String.valueOf(statusCode));
                }

                String content = EntityUtils.toString(response.getEntity());
                response.close();
                return content;
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
            throw e;
        }
    }

    // POST请求调用 path(例)：/api/post_result
    public static String InternalCallPost(String path, String toServiceID, String body, HashMap<String, String> headers) throws Exception {
        // 从环境变量中获取源服务id（即当前服务id）
        String fromServiceID = System.getenv("SERVICE_ID");
        
        // 构造url
        String url = String.format("http://%s-%s.inner-call.dyc.ivolces.com%s", fromServiceID, toServiceID, path);

        // 构造POST请求体
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));

        // 添加header
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // 执行POST请求并读取响应
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                // 判断http状态码是否成功
                if (statusCode != 200) {
                    response.close();
                    throw new Exception(String.valueOf(statusCode));
                }
                String content = EntityUtils.toString(response.getEntity());
                return content;
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
            throw e;
        }
    }
}